﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JasLib.Extensions;

namespace JasLib.Interop.Win32
{
    public static class Shell32Helper
    {
        /***************************************************************************/
        /// <summary>
        /// This function is a euphemism for "move files to the Recycle Bin" but is not a perfect
        /// abstraction because a proper move would involve IDropTarget.
        /// </summary>
        public static void DeleteFilesAllowUndo(params string[] filePaths)
        {
            SHFILEOPSTRUCT fileStruct = new SHFILEOPSTRUCT
            {
                hwnd = USER32.GetActiveWindow(),
                fFlags = FILEOP_FLAGS.FOF_NO_UI | FILEOP_FLAGS.FOF_ALLOWUNDO,
                wFunc = ShellFileOperationCode.FO_DELETE,
                pFrom = InteropUtilities.JoinDoubleNullTerminated(filePaths),
                fAnyOperationsAborted = true,
            };

            int iResult = SHELL32.SHFileOperation(ref fileStruct);

            /// The return value might be a GetLastError() constant but also might not.
            if (iResult != 0)
            {
                throw new Exception("shell32.dll!SHFileOperation() failed with error code {0} on these file(s): \"{0}\"."
                    .FormatWith(iResult, filePaths.Join("\", \"")));
            }

            return;
        }
    }
}
